package com.nintendo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nintendo.api.clients.FileMicroServiceFeign;
import com.nintendo.exceptions.GraceException;
import com.nintendo.mapper.UsersMapper;
import com.nintendo.pojo.Users;
import com.nintendo.pojo.bo.ModifyUserBO;
import com.nintendo.pojo.bo.RegistLoginBO;
import com.nintendo.pojo.vo.UsersVO;
import com.nintendo.result.ResponseStatusEnum;
import com.nintendo.service.UsersService;
import com.nintendo.task.SmsTask;
import com.nintendo.utils.DesensitizationUtil;
import com.nintendo.utils.JwtUtils;
import com.nintendo.utils.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.nintendo.base.BaseInfoProperties.*;

@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {
    @Autowired
    private SmsTask smsTask;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private SnowFlake snowFlake;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private FileMicroServiceFeign fileMicroServiceFeign;
    @Override
    public String sendCode(String mobile, HttpServletRequest request) {
        if(Objects.isNull(mobile)||"".equals( mobile)){
            GraceException.display(ResponseStatusEnum.USER_MOBILE_NULL);
        }
        return smsTask.sendSms(mobile,request);
    }

    @Override
    public UsersVO login(RegistLoginBO registLoginBO) {
        Object userCode = redisTemplate.opsForValue().get(USER_MOBILE_CODE + registLoginBO.getMobile());
        System.out.println("验证码====>"+userCode);
        System.out.println("用户传递的验证码===>"+ registLoginBO.getSmsCode());
        if(!registLoginBO.getSmsCode().equals(userCode)){
            GraceException.display(ResponseStatusEnum.USER_MOBILE_CODE_ERROR);
        }
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getMobile,registLoginBO.getMobile());
        Users isUsers = getOne(queryWrapper);

        if(Objects.nonNull(isUsers)){
            UsersVO usersVO = BeanUtil.copyProperties(isUsers, UsersVO.class);
            String userToken = jwtUtils.generateToken(isUsers.getMobile(), isUsers.getId());
            usersVO.setUserToken(userToken);
            redisTemplate.opsForValue().set(USER_TOKEN_PREFIX + isUsers.getId(),userToken,2,TimeUnit.HOURS);
            return usersVO;
        }
        Users users = createUsers(registLoginBO);
        UsersVO usersVO = BeanUtil.copyProperties(users, UsersVO.class);
        String userToken = jwtUtils.generateToken(users.getMobile(), users.getId());
        usersVO.setUserToken(userToken);
        redisTemplate.opsForValue().set(USER_TOKEN_PREFIX + users.getId(),userToken,2,TimeUnit.HOURS);
        return usersVO;
    }

    @Override
    public UsersVO modifyUserInfo(ModifyUserBO modifyUserInfo,HttpServletRequest request) {
        String userId = request.getHeader("userId");
        if(!modifyUserInfo.getUserId().equals(userId)){
            GraceException.display(ResponseStatusEnum.USER_NOT_EXIST);
        }
        Users users = BeanUtil.copyProperties(modifyUserInfo, Users.class);
        users.setId(userId);
        users.setUpdatedTime(LocalDateTime.now());
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getId,userId);
        if(modifyUserInfo.getWechatNum()!=null){
            Object limitUpdateWechatNum = redisTemplate.opsForValue().get(USER_UPDATE_WECHATNUM_LIMIT + modifyUserInfo.getUserId());
            if(Objects.isNull(limitUpdateWechatNum)){
                usersMapper.updateById(users);
                redisTemplate.opsForValue().set(USER_UPDATE_WECHATNUM_LIMIT+modifyUserInfo.getUserId(),"1",365, TimeUnit.DAYS);
                Users laterUsers =  getOne(queryWrapper);
                String userToken = jwtUtils.generateToken(laterUsers.getMobile(), laterUsers.getId());
                UsersVO usersVO = BeanUtil.copyProperties(laterUsers, UsersVO.class);
                usersVO.setUserToken(userToken);
                redisTemplate.opsForValue().set(USER_TOKEN_PREFIX + laterUsers.getId(),userToken,2,TimeUnit.HOURS);
                return usersVO;
            }else{
                GraceException.display(ResponseStatusEnum.USER_UPDATE_WECHATNUM_LIMIT);
            }
        }
        System.out.println("修改用户信息===>"+users);

        usersMapper.updateById(users);
        Users laterUsers = getOne(queryWrapper);
        String userToken = jwtUtils.generateToken(laterUsers.getMobile(), laterUsers.getId());
        UsersVO usersVO = BeanUtil.copyProperties(laterUsers, UsersVO.class);
        usersVO.setUserToken(userToken);
        redisTemplate.opsForValue().set(USER_TOKEN_PREFIX + laterUsers.getId(),userToken,2,TimeUnit.HOURS);
        return usersVO;
    }

    private Users createUsers(RegistLoginBO registLoginBO) {
        // TODO 远程调用文件服务 生成用户二维码
        Users users = new Users();
        users.setId(String.valueOf(snowFlake.nextId()));
        users.setMobile(registLoginBO.getMobile());
        users.setNickname(registLoginBO.getNickname());
        users.setFace("https://i.loli.net/2020/09/07/5QZqZwXZQyZqZqZ.png");
        String wechatNum = UUID.randomUUID().toString().replace("-", "").substring(0, 10);
        users.setWechatNum(wechatNum);
        String wechatNumUrl = fileMicroServiceFeign.generateQrCode(users.getId(), users.getWechatNum());
        users.setWechatNumImg(wechatNumUrl);
        users.setCreatedTime(LocalDateTime.now());
        users.setRealName(DesensitizationUtil.commonDisplay(registLoginBO.getMobile()));
        users.setUpdatedTime(LocalDateTime.now());
        users.setSex(3);
        users.setBirthday(LocalDate.now());
        users.setCountry("中国");
        users.setProvince("广东");
        users.setCity("深圳");
        users.setDistrict("深圳");
        users.setChatBg("https://i.loli.net/2020/09/07/5QZqZwXZQyZqZqZ.png");
        users.setFriendCircleBg("https://i.loli.net/2020/09/07/5QZqZwXZQyZqZqZ.png");
        users.setSignature("这个人很懒，什么都没留下");
        save(users);
        return users;
    }
}
